//
//  JrdOfflineCourseViewController.m
//  v2ex-iOS
//
//  Created by longcheng on 16/5/20.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdOfflineCourseViewController.h"
#import "JrdCommon.h"
#import "JRDCourseCell.h"
#import "JrdCourseDetailViewController.h"
#import "MJRefresh.h"
#import "CKHttpCommunicate.h"
#import "JZCateModel.h"
#import "LiuXSegmentView.h"
#import "LCCSqliteManager.h"
#import "JrdDatamanager.h"
@interface JrdOfflineCourseViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *courseDownloaded;
    NSMutableArray *courseDownloading;
    NSInteger segSelectType;
    NSInteger _page;/**< 页数 */
    NSInteger _limit;/**< 每页的个数 */
    NSInteger _charge;/**< 1：免费；2：收费 */
    NSArray* courseSel;
    LCCSqliteManager* manager;
}
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) UITableView* tableView;

@end

@implementation JrdOfflineCourseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    
    [self initData];
    manager = [LCCSqliteManager shareInstance];
    //[manager openSqliteFile:@"database"];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadData)
                                                 name:kUpdateDownloadInfoNotification
                                               object:nil];
 }
- (void)reloadData{
    NSString * searchCondition = [NSString stringWithFormat:@"is_operated=%@ and user_id=%@",
                                  @(1),[JrdDatamanager manager].user.userId];
    courseSel= [manager searchDataFromSheet:@"courselist" where:searchCondition];
    [self.tableView reloadData];
}


- (void)initData{
    segSelectType = 1;
    _page = 1;
    _limit = 20;
    _charge = 1;
}

- (void)viewDidAppear:(BOOL)animated{
    NSString * searchCondition = [NSString stringWithFormat:@"is_operated=%@ and user_id=%@",
                                  @(1),[JrdDatamanager manager].user.userId];
    courseSel= [manager searchDataFromSheet:@"courselist" where:searchCondition];
    self.sc_navigationItem.title = NSLocalizedString(@"v2_offline_course",nil);//@"我们学习";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadView{
    [super loadView];
    [self configureNavibarItems];
    [self configureSegTable];
    [self configureTable];
}

#pragma mark - Navigation
- (void)configureNavibarItems {
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico-menu"] highlight:[UIImage imageNamed:@"ico-menu"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowMenuNotification object:nil];
    }];
}

#pragma mark - segmentcontroller
- (void)configureSegTable{
    
    UIView* segView = [[UIView alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT+NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, STUDY_VIEW_SECTION_H)];
    [segView setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:segView];
    
    LiuXSegmentView *view=[[LiuXSegmentView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)        titles:@[NSLocalizedString(@"v2_download",nil),NSLocalizedString(@"v2_downloading", nil)]
                                                        offset: 20
        clickBlick:^void(NSInteger index) {
            [self tagClick:index];
    }];
    [segView addSubview:view];

}

- (void)tagClick:(NSInteger)index{
    segSelectType = index;
    
    if((0 == segSelectType && nil == courseDownloaded)){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
    
    if(1 == segSelectType && nil == courseDownloading){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }

}

- (void)segmentedControlChangedValue: (UISegmentedControl*)sendrer{
    segSelectType = sendrer.selectedSegmentIndex;
    return;//just for test
    if((0 == segSelectType && nil == courseDownloaded)){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
    
    if(1 == segSelectType && nil == courseDownloading){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - set table

-(void)configureTable{
    int table_y = STATUS_BAR_HEIGHT+NAVIGATION_BAR_HEIGHT+STUDY_VIEW_SECTION_H;//_section_view.frame.origin.y + _section_view.frame.size.height;
    self.tableView                 = [[UITableView alloc] initWithFrame:CGRectMake(0, table_y, SCREEN_WIDTH, SCREEN_HEIGHT - table_y) style:UITableViewStylePlain];
    //self.tableView.style = UITableViewStylePlain;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setupTableview];
}

- (void)loadNewData{
    _page = 1;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //[self getCourseData];
    });
    
}

- (void)loadMoreData{
    _page++;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseData];
    });
    
}
- (void)getCourseData{
    NSDictionary *parameter;
    if(0 == segSelectType){
        parameter = @{@"mod":@"search",
                      @"act":@"mobile",
                      @"from":@"iPhone",
                      @"page":[NSString stringWithFormat:@"%ld",_page],
                      @"limit":[NSString stringWithFormat:@"%ld",_limit],
                      @"today":@"1",
                      @"charge":[NSString stringWithFormat:@"%ld",_charge],
                      };
    }else{
        parameter = @{@"mod":@"search",
                      @"act":@"mobile",
                      @"from":@"iPhone",
                      @"page":[NSString stringWithFormat:@"%ld",_page],
                      @"limit":[NSString stringWithFormat:@"%ld",_limit],
                      @"cateid":@"72351176527446016",
                      @"charge":[NSString stringWithFormat:@"%ld",_charge],
                      };
        
    }
    
    __weak typeof(self) weakself = self;
    [CKHttpCommunicate createRequest:HTTP_IMANDARIN_NULL WithParam:parameter withMethod:GET success:^(id result) {
        if (result) {
            NSMutableArray *ClassListArray = [result objectForKey:@"ClassList"];
            if(0 == segSelectType){
                if(nil == courseDownloaded){
                    courseDownloaded = [[NSMutableArray alloc] init];
                }
                
                if(1 == _page){
                    [courseDownloaded removeAllObjects];
                }
                for (int i = 0; i < ClassListArray.count; i++) {
                    JZCateModel *jzCateM = [ClassListArray objectAtIndex:i];
                    [courseDownloaded addObject:jzCateM];
                }
            }else{
                if(nil == courseDownloading){
                    courseDownloading = [[NSMutableArray alloc] init];
                }
                
                if(1 == _page){
                    [courseDownloading removeAllObjects];
                }
                for (int i = 0; i < ClassListArray.count; i++) {
                    JZCateModel *jzCateM = [ClassListArray objectAtIndex:i];
                    [courseDownloading addObject:jzCateM];
                }
                
            }
            NSLog(@"result:%@",result);
        }
        [weakself.tableView reloadData];
        [weakself.tableView.mj_header endRefreshing];
        [weakself.tableView.mj_footer endRefreshing];
    } failure:^(NSError *erro) {
        
    } showHUD:nil];
    
}


-(void)setupTableview{
    //MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //设置普通状态的动画图片
    /*NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; ++i) {
        //        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%zd",i]];
        //        [idleImages addObject:image];
        UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [idleImages addObject:image];
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    //设置即将刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
    [refreshingImages addObject:image1];
    UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
    [refreshingImages addObject:image2];
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;*/
    //马上进入刷新状态
    //[self.tableView.mj_header beginRefreshing];
    //上拉刷新
    //self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (segSelectType == 1) {
        return courseSel.count;
    }else{
        return courseDownloading.count;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return JRD_COURSE_TABLE_H;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndentifier = @"courseCell2";
    JRDCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if (cell == nil) {
        cell = [[JRDCourseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        //下划线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 71.5, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = JRD_RGB(200, 199, 204);
        [cell addSubview:lineView];
    }
    
    JrdCourseModel *jrdCourseM = [[JrdCourseModel alloc] init];
    jrdCourseM.courseName = courseSel[indexPath.row][COURSE_NAME];//[courseSel[indexPath.row] valueForKey:@"course"];
    jrdCourseM.courseDes =[NSString stringWithFormat:@"%@ ~ %@",courseSel[indexPath.row][COURSE_STARTDATE],courseSel[indexPath.row][COURSE_ENDDATE]];
    jrdCourseM.coursePhoto = [NSString stringWithFormat:@"http://120.55.86.220/%@",courseSel[indexPath.row][COURSE_ICON_URL]];
    
    [cell setJzCourseM:jrdCourseM];
    
    int studyPercent = 0;
    // calc the study percent
    NSString * searchCondition = [NSString stringWithFormat:@"node_parentid=%@ and user_id=%@",
                                  courseSel[indexPath.row][COURSE_ID],[JrdDatamanager manager].user.userId];
    NSArray* array = [manager searchDataFromSheet:@"nodelist" where:searchCondition];
    if(nil!= array && 0!=array.count)
    {
        float  toatal_time = 0;
        float  study_time = 0;
        for(int i = 0; i < array.count; i++){
            NSString* total = array[i][NODE_TOTAL_TIME];
            NSString* study = array[i][NODE_STUDY_TIME];
            toatal_time += [total floatValue];
            study_time += [study floatValue];
        }
        if(0 == toatal_time){
            [cell setPercent:0];
        }else{
            studyPercent = study_time*100/toatal_time;
            [cell setPercent:studyPercent];

        }
    }else{
        [cell setPercent:0];
    }
    return cell;

}


#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"didselect row ");
    JrdCourseModel* jrdCoursmodel = [[JrdCourseModel alloc] init];
    jrdCoursmodel.courseName = courseSel[indexPath.row][COURSE_NAME];//[courseSel[indexPath.row] valueForKey:@"course"];
    jrdCoursmodel.courseDes =courseSel[indexPath.row][COURSE_DES];
    NSString* url_icon = courseSel[indexPath.row][COURSE_ICON_URL];
    jrdCoursmodel.coursePhoto = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_icon];
    jrdCoursmodel.courseId = courseSel[indexPath.row][COURSE_ID];
    jrdCoursmodel.courseStartTime =courseSel[indexPath.row][COURSE_STARTDATE];
    jrdCoursmodel.courseEndTime =courseSel[indexPath.row][COURSE_ENDDATE];
    JrdCourseDetailViewController* vc = [[JrdCourseDetailViewController alloc] init];
    vc.coursemodel = jrdCoursmodel;
    vc.enter_type = ENTER_FROM_DOWNLOAD;
    [self.navigationController pushViewController:vc animated:YES];
    return;

}

#pragma mark - setFakeData
- (void)setFakeData{
    courseDownloaded = [[NSMutableArray alloc] init];
    courseDownloading = [[NSMutableArray alloc] init];
    //courseReconmmend = [[NSMutableArray alloc] init];
    
    //读取plist文件获取假数据
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"classCategory" ofType:@"plist"];
    courseDownloaded = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    
    //课程类型
    NSString *iCategoryListPath = [[NSBundle mainBundle] pathForResource:@"courseSel" ofType:@"plist"];
    courseDownloading = [[NSMutableArray alloc] initWithContentsOfFile:iCategoryListPath];
    
    //NSString *recommendPath = [[NSBundle mainBundle] pathForResource:@"classCategory" ofType:@"plist"];
    //courseReconmmend = [[NSMutableArray alloc] initWithContentsOfFile:recommendPath];
}

@end
